# -*- coding: UTF-8 -*-
import requests
import json
from bean.hot_new import HotNew
from typing import List
import traceback
import urllib.parse
from news_platform.plat.web_platform import WebPlatform


base_url = "https://m.weibo.cn/search?containerid=100103type=1&t=10&q="

api_url = "https://m.weibo.cn/api/container/getIndex?" \
          "containerid=106003type%3D25%26t%3D3%26disable_hot%3D1%26filter_type%3Drealtimehot"

app_path = "pages/topic/topic?topicContent=#{0}#&containerid=231522type%3D1%26q{1}&fromPage=feedHotSearch"

# pages/topic/topic?topicContent=#守护你回家的路#&containerid=231522
# type%3D1%26q%3D%23%E5%AE%88%E6%8A%A4%E4%BD%A0%E5%9B%9E%E5%AE%B6%E7%9A%84%E8%B7%AF%23&fromPage=feedHotSearch


class WeiBo(WebPlatform):

    def __init__(self):
        self.name = "微博热搜"

    def query_hot_news(self):

        result: List[HotNew] = []
        try:
            response = requests.get(api_url)
            data = json.loads(response.content)
            if data['ok'] != 1:
                news = []
            else:
                news = data['data']['cards'][0]['card_group']
            serial_no = 0
            for new in news:
                title = new['desc']
                # link = str(new['scheme'])
                link = base_url + title
                summary = ''
                summary_url = ''
                try:
                    summary_url = 'https://m.s.weibo.com/ajax_topic/detail?q=%23' + str(title)
                    summary_resp = requests.get(summary_url)
                    summary_data = json.loads(summary_resp.content)
                    if summary_data['code'] == '100000':
                        summary_base_info = summary_data['data']['baseInfo']
                        if 'object' in summary_base_info:
                            summary = summary_base_info['object']['summary']
                    else:
                        summary = ''
                except Exception as e:
                    print(summary_url)
                    print(e)
                    print(traceback.format_exc())
                if 'desc_extr' in new and new['desc_extr'] != '':
                    ext_info = str(new['desc_extr']) + "热度"
                elif serial_no != 0:
                    continue
                else:
                    ext_info = "置顶"

                serial_no = serial_no + 1
                hot_new = HotNew(serial_no, title, link, "3", ext_info, summary)
                hot_new.app_path = app_path.format(title, urllib.parse.quote("=#{0}#".format(title)))
                result.append(hot_new)
        except Exception as e:
            print(e)
        return result

